package com.meego.common.util;

import java.math.BigInteger;
import java.util.Formatter;

public class HexUtil {

    public static char encodeHex(int i) {
        i &= 15;
        if (i >= 10) {
            return (char) (97 + (i - 10));
        }
        return (char) (48 + i);
    }

    public static int decodeHex(char c) {
        if ((c >= 'a') && (c <= 'f')) {
            return c - 'a' + 10;
        }
        if ((c >= 'A') && (c <= 'F')) {
            return c - 'A' + 10;
        }
        if ((c >= '0') && (c <= '9')) {
            return c - '0';
        }
        return 0;
    }

    public static byte[] get(String key) {
        byte[] bits = new byte[key.length() / 2];
        for (int i = 0; i < bits.length; i++) {
            bits[i] = (byte) (decodeHex(key.charAt(i * 2)) * 16 + decodeHex(key.charAt(i * 2 + 1)));
        }
        return bits;
    }

    public static BigInteger hexToBigInteger(String hexString) {
        return new BigInteger(1, get(hexString));
    }

    public static String bigIntegerToHex(BigInteger input) {
        return input.toString(16);
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);

        Formatter formatter = new Formatter(sb);
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        return sb.toString();
    }

    public static byte[] hexString2ByteArr(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static String byteArr2HexString(byte[] Source) throws Exception {
        String result = "";
        for (int i = 0; i < Source.length; i++) {
            result += Integer.toString((Source[i] & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }
}
